﻿using System.Collections.Generic;

namespace TemperatureConverter
{
    public class TemperatureConverter
    {
        
        private static readonly Dictionary<Temperature.TemperatureType, double> MultiplierFromC = new Dictionary<Temperature.TemperatureType, double>
        {
            {Temperature.TemperatureType.K, 1.0},
            {Temperature.TemperatureType.F, 1.8},
            {Temperature.TemperatureType.N, 0.33}
        };

        private static readonly Dictionary<Temperature.TemperatureType, double> AdditionFromC = new Dictionary<Temperature.TemperatureType, double>
            {
            {Temperature.TemperatureType.K, 273.15},
            {Temperature.TemperatureType.F, 32},
            {Temperature.TemperatureType.N, 0}
        };

        private static readonly Dictionary<Temperature.TemperatureType, double> MultiplierToC = new Dictionary<Temperature.TemperatureType, double>
            {
            {Temperature.TemperatureType.K, 1.0},
            {Temperature.TemperatureType.F, 5.0 / 9},
            {Temperature.TemperatureType.N, 100.0 / 33}
        };

        private static readonly Dictionary<Temperature.TemperatureType, double> AdditionToC = new Dictionary<Temperature.TemperatureType, double>
        {
            {Temperature.TemperatureType.K, -273.15},
            {Temperature.TemperatureType.F, -32.0 * 5 / 9},
            {Temperature.TemperatureType.N, 0}
        };

        private static double ConvertFromC(double value, Temperature.TemperatureType toType)
        {
            double result;
            if (toType == Temperature.TemperatureType.C)
                result = value;
            else
                result = value * MultiplierFromC[toType] + AdditionFromC[toType];
            return result;
        }       
        
        private static double ConvertToC(double value, Temperature.TemperatureType fromType)
        {
            double result;
            if (fromType == Temperature.TemperatureType.C)
                result = value;
            else
                result = value * MultiplierToC[fromType] + AdditionToC[fromType];
            return result;
        }

        public static Temperature Convert(Temperature from, Temperature.TemperatureType toType)
        {
            Temperature result;
            if (from.Type == toType)
                result = new Temperature(from.Value,from.Type);
            else
            {
                double temp = ConvertToC(from.Value,from.Type);
                temp = ConvertFromC(temp, toType);
                result = new Temperature(temp, toType);
                
            }
            return result;
        }
    }
}
